import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Checkbox, Typography, Space, Divider, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { CustomFrame } from '../components/CustomFrame';
import { useNavigate } from 'react-router-dom';
import { login } from '../services/auth';
import { LoginParams } from '../types/auth';
import { AxiosError } from 'axios';

const { Title } = Typography;

export const LoginPage: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  // 检查更新
  useEffect(() => {
    const checkForUpdates = async () => {
      try {
        const updateInfo = await window.electronAPI.runTask('get-update-info');
        if (updateInfo) {
          navigate('/update');
        }
      } catch (error) {
        console.error("启动检查更新失败:", error);
      }
    };
    checkForUpdates();
  }, [navigate]);

  // 实现"记住我"功能：组件加载时，尝试从本地存储读取凭据
  useEffect(() => {
    const fetchRememberedCredentials = async () => {
      try {
        const rememberedCredentials = await window.electronAPI.runTask('store:get', 'rememberedCredentials') as LoginParams;
        if (rememberedCredentials && rememberedCredentials.username) {
          form.setFieldsValue({
            username: rememberedCredentials.username,
            password: rememberedCredentials.password,
            remember: true
          });
        }
      } catch (error) {
        console.error("获取记住的凭证失败:", error);
      }
    };
    fetchRememberedCredentials();
  }, [form]);

  const onFinish = async (values: LoginParams) => {
    setLoading(true);
    try {
      const response = await login({ username: values.username, password: values.password });
      const { token } = response.data.data;
      await window.electronAPI.runTask('store:set', 'token', token);
      
      message.success('登录成功');

      if (values.remember) {
        await window.electronAPI.runTask('store:set', 'rememberedCredentials', { username: values.username, password: values.password });
      } else {
        await window.electronAPI.runTask('store:delete', 'rememberedCredentials');
      }

      navigate('/app');
    } catch (error) {
      const axiosError = error as AxiosError<{ message: string }>;
      const errorMessage = axiosError.response?.data?.message || '登录失败，请检查您的网络或联系管理员';
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <CustomFrame title="用户登录">
      <div style={{ 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center', 
        padding: '32px', 
        height: '100%',
        boxSizing: 'border-box'
      }}>
        <Space direction="vertical" align="center" style={{ width: '100%', flex: 1, justifyContent: 'center' }}>
          <Title level={3} style={{ color: 'rgba(255, 255, 255, 0.85)', marginBottom: '32px' }}>CursorTool</Title>
          <Form
            form={form}
            name="normal_login"
            style={{ width: '300px' }}
            initialValues={{ remember: false }}
            onFinish={onFinish}
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入您的用户名!' }]}
            >
              <Input prefix={<UserOutlined style={{ color: 'rgba(255, 255, 255, 0.45)' }} />} placeholder="用户名" size="large" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入您的密码!' }]}
            >
              <Input.Password
                prefix={<LockOutlined style={{ color: 'rgba(255, 255, 255, 0.45)' }} />}
                type="password"
                placeholder="密码"
                size="large"
              />
            </Form.Item>
            <Form.Item>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading} style={{ width: '100%' }} size="large" block>
                登 录
              </Button>
            </Form.Item>
          </Form>
        </Space>
        <Divider style={{ margin: '16px 0' }}>
            <span style={{color: 'rgba(255, 255, 255, 0.45)'}}>没有账户?</span>
        </Divider>
        <Button type="link" onClick={() => navigate('/register')}>立即注册</Button>
      </div>
    </CustomFrame>
  );
}; 